import os
import re


_ESCAPE = re.compile('.*[\\*?].*')


def get_file_paths(path_pattern):
    """
    Get a list of file paths.
    :param path_pattern the pattern of the path. User can use '*' and '?' as escape character in the pattern. '*' matches
    with zero or any number of characters. '?' matches with only one character.
    E.g. "/abc/*xyz/def??.jpg" means all files which path matches with the pattern, such as "/abc/pqrsxyz/defaabb.jpg".
    """
    ps = _pattern_split(path_pattern)
    roots = ['/' if len(ps[0]) == 0 else ps[0]]
    del ps[0]

    if len(ps[-1]) == 0:
        del ps[-1]

    global _ESCAPE
    for p in ps:
        roots = [r + os.sep + p for r in roots] if _ESCAPE.match(p) is None else \
                [r + os.sep + name for r in roots if os.path.isdir(r) for name in os.listdir(r) if _match(name, 0, len(name), p, 0, len(p))]

    result = []
    for p in roots:
        if os.path.isfile(p):
            result.append(p)
        elif os.path.isdir(p):
            for f in os.listdir(p):
                result.append(p + os.sep + f)
    return result


def _pattern_split(pattern):
    res = pattern.split('/')
    return [e for s in res for e in s.split('\\')]


def _match(s, ss, se, p, ps, pe):
    if ps >= pe:
        return ss == se
    ch = p[ps]
    if ch == '?':
        return se > ss and _match(s, ss+1, se, p, ps+1, pe)
    if ch == '*':
        return se > ss and _match(s, ss+1, se, p, ps, pe) or _match(s, ss, se, p, ps+1, pe)
    return se > ss and ch == s[ss] and _match(s, ss+1, se, p, ps+1, pe)


def get_parent_directory(path: str):
    pos = path.rfind('/')
    if pos < 0:
        pos = path.rfind('\\')
        if pos < 0:
            return '.'
    return path[:pos]


def to_standard_directory(path: str):
    if path is None:
        return None
    if path[-1] in ('/', '\\'):
        path = path[:-1]
    return path
